package com.rabbit.exampl2;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

/**
 * 运行两次，即同时让两个实例在跑
 */
public class Worker {
	private static final String QUEUE_NAME = "hello";
	private static final String HOST = "192.168.21.135";
	private static final int PORT = 5672;
	private static final String USERNAME = "ceshi";
	private static final String PASSWORD = "123456";
	private static final String VIRTUALHOST = "/";

	public static void main(String[] args) throws IOException, TimeoutException {

		// <1>创建连接工厂
		ConnectionFactory factory = new ConnectionFactory();
		// <2>指定连接的broker Server地址，以及联接用户名和virtualhost
		factory.setHost(HOST);
		factory.setPort(PORT);
		factory.setUsername(USERNAME);
		factory.setPassword(PASSWORD);
		factory.setVirtualHost(VIRTUALHOST);

		// <3>与broker建立tcp联接。
		Connection connection = factory.newConnection();
		// <4>在tcp联接上建立通道，通道可以建立多个
		Channel channel = connection.createChannel();
		// <5>通道上声明队列
		channel.queueDeclare(QUEUE_NAME, // 队列名称
				false, // 消息是否持久化
				false, // 队列是否由该通道独占，意思是基他的channel不能声明该queue,即不能使用其发送消息
				false, // 消息是否自动删除
				null);// queue的一些其他的属性
		
		//channel.basicQos(1); //指定队列接收消息的权重。
		
		Consumer consumer = new DefaultConsumer(channel) {
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
					byte[] body) throws IOException {
				String message = new String(body, "UTF-8");
				System.out.println(" [x] Received '" + message + "'");
				try {
					doWork(message);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally{
					System.out.println(" [x] Done");
				}
			}
		};
		//<6>绑定一个消费者，到队列
		boolean autoAck = true; //自动确认接收到了消息
		channel.basicConsume(QUEUE_NAME, autoAck, consumer);
		
		//下面两句不要增加，加上后，消费者立即关闭通道和联接，看不到接收消息打印
		//channel.close();
		//connection.close();

	}
	
	private static void doWork(String task) throws InterruptedException {
	    for (char ch: task.toCharArray()) {
	        if (ch == '.') Thread.sleep(1000);
	    }
	} 
}
